#!/usr/bin/env python3

#  VT码命令前缀
PR = '\033['

#  光标操作定义
SAVE, LOAD, HIDE, SHOW = 's', 'u', '?25l', '?25h'

#  清除操作定义
SCREEN, LINE, END = '2J', '2K', 'K'

#  颜色定义
BLACK, RED, GREEN, YELLOW, BLUE, PURPLE, CYAN, WHITE, DEFAULT = range(9)

#  方向定义
UP, DOWN, LEFT, RIGHT = "ABDC"


#  绝对定位
def goto(r, c):
    print("%s%d;%dH" % (PR, r, c), end='', flush=True)

#  相对定位
def move(direction, step):
    print("%s%d%s" % (PR, step, direction), end='', flush=True)

def left(step):
    move(LEFT, step)

def right(step):
    move(RIGHT, step)

def up(step):
    move(UP, step)

def down(step):
    move(DOWN, step)

#  光标操作
def run(cmd):
    print("%s%s" % (PR, cmd), end='', flush=True)

def save():
    run(SAVE)

def load():
    run(LOAD)

def hide():
    run(HIDE)

def show():
    run(SHOW)

#  清除操作
def clear():
    run(SCREEN)

def clearLine():
    run(LINE)

def clearLineEnd():
    run(END)

#  颜色输出
def setColor(fg, bg, bold):
    if bold:
        print("%s%d;%d;1m" % (PR, fg + 30, bg + 40), end='', flush=True)
    else:
        print("%s%d;%dm" % (PR, fg + 30, bg + 40), end='', flush=True)

def color(s, fg, bg, bold):
    if bold:
        print("%s%d;%d;1m%s\033[0m" % (PR, fg + 30, bg + 40, s),
                end='', flush=True)
    else:
        print("%s%d;%dm%s\033[0m" % (PR, fg + 30, bg + 40, s),
                end='', flush=True)

def clearStyle():
    print("%s0m" % (PR), end='', flush=True)


#  vt测试
if __name__ == "__main__":
    clear()
    goto(1, 1)
    run(HIDE)
    setColor(RED, DEFAULT, False)
    print("1hello world")
    clearStyle()
    print("2hello world")
    color("3hello world", YELLOW, BLACK, True)
    input()
    run(SHOW)



